package com.jtjrenren.android.taxi.passenger.utils;


import android.content.Context;
import android.text.TextUtils;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.jtjrenren.android.taxi.passenger.Constants;
import com.jtjrenren.android.taxi.passenger.R;
import com.jtjrenren.android.taxi.passenger.base.BaseApplication;
import com.jtjrenren.android.taxi.passenger.bean.AddressInfo;
import com.jtjrenren.android.taxi.passenger.bean.api.ApiCommonT;
import com.jtjrenren.android.taxi.passenger.bean.event.AliPayEvent;
import com.jtjrenren.android.taxi.passenger.manger.AppManger;
import com.jtjrenren.android.taxi.passenger.manger.pay.ali.PayResult;
import com.jtjrenren.android.taxi.passenger.manger.push.cmd.Protocl;
import com.library.utils.Base64;
import com.library.utils.CipherUtils;
import com.library.utils.GsonUtils;
import com.library.utils.StringUtils;
import com.tencent.mm.sdk.modelbase.BaseResp;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import datetime.DateTime;

/**
 * Created by wdl on 2015/12/10.
 */
public class ModuleUtils {

    /**
     * 对于微信支付返回结果的处理
     *
     * @param event
     * @return null 表示支付成功 ，不为null 则代表有错误信息
     */
    public static String handWeixinPayResult(BaseResp event) {
        String result = null;
        if (event.errCode == 0) {

        } else if (event.errCode == -1 || event.errCode == -2) {
            result = "支付失败";
        }
        return result;
    }

    /**
     * 支付宝的支付结果确认
     *
     * @param event
     * @return null 表示支付成功 ，不为null 则代表有错误信息
     */
    public static String handAliPayResult(AliPayEvent event) {
        String result = null;
        PayResult aliResult = new PayResult(event.getResult());
        String payStatus = aliResult.getResultStatus();

        if (TextUtils.equals(payStatus, "9000")) {

        } else if (TextUtils.equals(payStatus, "8000")) {
            result = "支付结果确认中";
        } else {
            result = "支付失败";
        }
        return result;
    }

    public static String getHtmlUrl(String desc) {
        String url = AppManger.getInstance().getString(R.string.url_base_html);
        url = url + "?" + "__ct=" + AppManger.getInstance().getString(R.string.unicode) + "&fn=" + desc;
        return url;
    }

    public static boolean handCommon(int code) {
        if (code == 1)
            return true;
        else if (code == 11) {
            //tokent失效，需要重新获取
            AppManger.getInstance().getToken(true);
        }
        return false;
    }

    //
    public static <T> ApiCommonT getCommonApi(String json, Class<T> clazz) {
        ApiCommonT<T> apiCommonT = null;
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
            apiCommonT = new ApiCommonT<>();
            int code = jsonObject.getInt("code");
            String msg = jsonObject.getString("msg");
            String data = jsonObject.getString("data");
            if (!StringUtils.isEmpty(data)) {
                List list = GsonUtils.fromJsonArray(data, clazz);
                apiCommonT.setData(list);
            }
            apiCommonT.setCode(code);
            apiCommonT.setMsg(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonObject = null;
        return apiCommonT;
    }

    public static String getStrFromResource(int id) {
        return BaseApplication.getInstance().getResources().getString(id);
    }

    public static String getStrFromResource(Context context, int id) {
        return context.getResources().getString(id);
    }

    /**
     * 保留小数点后几位
     *
     * @param numStr
     * @param n      小数点后几位
     * @return
     */
    public static double formatPoint(double numStr, int n) {
        BigDecimal temp = new BigDecimal(numStr);
        double num = temp.setScale(n, BigDecimal.ROUND_HALF_UP).doubleValue();

        return num;
    }

    public static String getFridenlyTime(Date date) {
        DateTime currentTime = new DateTime(new Date());
        DateTime diyTime = new DateTime(date);

        String qz = "MM-dd HH:mm";
        if (currentTime.getMonth() == diyTime.getMonth() && currentTime.getDay() == diyTime.getDay()) {
            if (diyTime.getHour() < 12 && diyTime.getHour() >= 0)
                qz = "上午 hh:mm";
            else
                qz = "下午 hh:mm";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(qz);
        return simpleDateFormat.format(date);
    }


    public static int getPayStatus(String payStatus) {
        int statuss = -1;
        if (StringUtils.isEmpty(payStatus))
            statuss = -1;
        else statuss = Integer.parseInt(payStatus);
        return statuss;
    }

    /**
     * 根据反地理编码，确定要显示的该地点的位置名称
     *
     * @param result
     */
    public static String getMapShowLocMsgByRr(ReverseGeoCodeResult result) {
        PoiInfo nearestPoi = getNearestPoi(result.getLocation(), result.getPoiList(), 100);
        StringBuilder sb = new StringBuilder();
        ReverseGeoCodeResult.AddressComponent addressDetail = result.getAddressDetail();
        sb.append(addressDetail.district).append(addressDetail.street);
        if (nearestPoi != null)
            sb.append(nearestPoi.name);
        else
            sb.append(addressDetail.streetNumber);
        return sb.toString();
    }

    /**
     * 获取某个点附近最近的poi位置
     *
     * @param loc
     * @param poiList
     * @param len     是否需要设定相关距离  [0]最远距离，假如最近的位置超过这个距离则返回null,单位 米
     */
    public static PoiInfo getNearestPoi(LatLng loc, List<PoiInfo> poiList, int... len) {
        if (poiList == null)
            return null;
        double minDistance = 0, currentDistance;
        PoiInfo minInfo = null, info;
        for (int i = 0; i < poiList.size(); i++) {
            info = poiList.get(i);
            currentDistance = DistanceUtil.getDistance(loc, info.location);
            if (i == 0)
                minDistance = currentDistance;
            if (currentDistance <= minDistance) {
                minDistance = currentDistance;
                minInfo = info;
            }
        }
        if (len.length > 0) {
            if (minDistance > len[0]) {
                return null;
            }
        }
        return minInfo;
    }


    /**
     * des解密(%2B为服务器自动转换的)
     *
     * @param str
     * @return
     */
    public static String DesDecrypt(String str) {
        str = str.replaceAll("%2B", "+");
        try {
            return CipherUtils.decryptDES(Base64.decode(str),
                    Constants.DES_KEY,
                    Constants.DES_IV);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * des加密
     *
     * @param str
     * @return
     */
    public static String DesEncry(String str) {
        try {
            byte[] encryptDES = CipherUtils.encryptDES(str,
                    Constants.DES_KEY,
                    Constants.DES_IV);
            return Base64.encode(encryptDES);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 将从timepiker中获取的时间字符串转换为指定的时间格式(2016-01-25 12:30:00.754)
     *
     * @param format
     * @return
     */
    public static String convertTimpiker(String format, String dateStr) {
        String result = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date parseDate = simpleDateFormat.parse(dateStr);
            simpleDateFormat = new SimpleDateFormat(format);
            result = simpleDateFormat.format(parseDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Date getTimpikerDate(String dateStr) {
        Date result = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            result = simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取收费标准的定制url
     *
     * @param lat
     * @param lng
     * @param carType
     */
    public static String getSfBzUrl(String lat, String lng, String carType) {
        return Constants.CONFIG_URL_SFBZ.replaceFirst("###", lat).replaceFirst("###", lng).replaceFirst("###", carType);
    }


    /**
     * 将百度地图的poi信息列表转换为地址位置列表
     *
     * @param poiInfoList
     * @return
     */
    public static List<AddressInfo> convertPoiListToAddresList(List<PoiInfo> poiInfoList) {
        List<AddressInfo> list = new ArrayList<>();
        if (!(poiInfoList == null || poiInfoList.size() == 0)) {
            AddressInfo addressInfo;
            for (PoiInfo info : poiInfoList) {
                addressInfo = new AddressInfo();
                addressInfo.setName(info.name);
                addressInfo.setAddr(info.address);
                addressInfo.setLati(info.location.latitude + "");
                addressInfo.setLongi(info.location.longitude + "");

                list.add(addressInfo);
            }
        }
        return list;
    }


    /**
     * 将百度地图的推荐结果转化为位置列表
     *
     * @param sugList
     * @return
     */
    public static List<AddressInfo> convertSugListToAddresList(List<SuggestionResult.SuggestionInfo> sugList) {
        List<AddressInfo> list = new ArrayList<>();
        if (sugList == null || sugList.size() == 0)
            return list;
        AddressInfo addressInfo;
        for (SuggestionResult.SuggestionInfo info : sugList) {
            if (info.pt != null && !StringUtils.isEmpty(info.key) && !StringUtils.isEmpty(info.city) && !StringUtils.isEmpty(info.district)) {
                addressInfo = new AddressInfo();
                addressInfo.setName(info.key);
                addressInfo.setAddr(info.city + info.district);
                addressInfo.setLati(info.pt.latitude + "");
                addressInfo.setLongi(info.pt.longitude + "");

                list.add(addressInfo);
            }
        }
        return list;
    }

    /**
     * 金额格式化
     *
     * @param value 如果expstr为空，则默认为###,###,###,###,##0.0
     * @return
     */
    public static String convertMoneyString(double value, String expstr) {
        if ("NaN".equals("" + value)) {
            return "0";
        }
        if (StringUtils.isEmpty(expstr)) {
            expstr = "###,###,###,###,##0.0";
        }
        DecimalFormat df = new DecimalFormat();
        df.applyPattern(expstr);
        return df.format(value);
    }

    /**
     * 英式金额格式化,带2位小数
     *
     * @param value
     * @return
     */
    public static String convertMoney2String(double value) {
        return convertMoneyString(value, "###,###,###,###,##0.00");
    }

    /**
     * 获取cmd命令的标志位位置
     *
     * @param cmd
     * @return
     */
    public static int[] getCmdFlagIndex(String cmd) {
        int length = cmd.length() / 2;
        String tmp;
        int fristIndex = -1, secondIndex = -1;
        for (int i = 0; i < length; i++) {
            tmp = cmd.substring(i * 2, i * 2 + 2).toUpperCase();
            if (Protocl.PROTOCOL_FLAG.equals(tmp)) {
                if (fristIndex < 0)
                    fristIndex = i * 2;
                else {
                    secondIndex = i * 2;
                    break;
                }
            }
        }
        int[] result = new int[2];
        result[0] = fristIndex;
        result[1] = secondIndex;
        return result;
    }

    /**
     * 将11.20 拆分成 11 .20
     *
     * @param cost
     * @return
     */
    public static String[] getCostDetails(String cost) {
        String[] split;
        if (cost.indexOf(".") < 0) {
            split = new String[2];
            split[0] = cost;
            split[1] = ".00";
            return split;
        }
        split = cost.split("\\.");
        String tmp = "." + split[1];
        if (split[1].length() < 2) {
            tmp += "0";
        }
        split[1] = tmp;
        return split;
    }

    /**
     * 格式化当前时间，默认格式 yyyy/mm/dd HH:mm:ss
     *
     * @param regex
     * @return
     */
    public static String formatNowDate(String regex) {
        String result = "";
        if (StringUtils.isEmpty(regex))
            regex = "yyyy/mm/dd HH:mm:ss";
        SimpleDateFormat format = new SimpleDateFormat(regex);
        result = format.format(new Date());

        return result;
    }

    public static boolean isOrderFinish(int order_status) {
        boolean result = false;
        if (order_status == Constants.ORDER_STATUS_CANCLE_BEFOREDISPATCH
                || order_status == Constants.ORDER_STATUS_CANCLE_AFTERDRIVER_ACCEPTE
                || order_status == Constants.ORDER_STATUS_CANCLE_BYDRIVER
                || order_status == Constants.ORDER_STATUS_FINISH_FORCE
                || order_status == Constants.ORDER_STATUS_CLOSE_BYPLATFORM)
            result = true;
        return result;
    }

    /**
     * 获取收费详情的预估费用
     *
     * @param startAddr
     * @param startLat
     * @param startLng
     * @param endAddr
     * @param endLat
     * @param endLng
     * @param carType
     * @param useCarTime
     * @param userID
     */
    public static String getCostDetailsUrl(String startAddr, String startLat, String startLng,
                                           String endAddr, String endLat, String endLng,
                                           String carType, String useCarTime, String userID) {
        String url = AppManger.getInstance().getString(R.string.url_base) + "/EstimatedCost.html?__from=android&startAddr=" + startAddr + "&startlng=" + startLng + "&startlat="
                + startLat + "&endAddr=" + endAddr + "&endlng=" + endLng + "&endlat=" + endLat + "&cartype=" + carType + "&userCarTime="
                + useCarTime + "&userId=" + userID;
        return url;
    }


}
